(function (factory) {

    if (typeof module === 'object' && module.export) {
        module.export = factory()
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {
        define([], factory)
    } else if (typeof window !== 'undefined') {
        window.IndexSidebar = factory()
    }

})(function () {

    var defaultOptions = {
        chars: '*ABCDEFGHIJKLMNOPQRSTUVWXYZ#',
        isAdjust: true,
        offsetTop: 70,
        offsetBottom: 10,
        lineScale: 0.7,
        charOffsetX: 80,
        charOffsetY: 20
    }

    function IndexSidebar(options) {
        options = options || {}

        for (var k in defaultOptions) {
            if (defaultOptions.hasOwnProperty(k)) {
                options[k] = options[k] || defaultOptions[k]
            }
        }

        this.options = options
        this.initialize(options)
    }

    IndexSidebar.prototype.initialize = function (options) {

        var chars = options.chars
        var el =  document.createElement('div')
        el.className = 'index-sidebar-container'
        el.innerHTML = this.render(chars)
        document.body.appendChild(el)

        this.el = el
        this.elChar = el.querySelector('.current-char')
        this.chars = chars
        if (options.isAdjust) {
            this.adjust(options)
        }
        this.initEvents(options)
    }

    IndexSidebar.prototype.render = function (chars) {
        return (
            '<span class="current-char"></span>' +
            '<ul>' +
            [].map.call(chars, function (ch) {
                return '<li>' + ch + '</li>'
            }).join('') +
            '</ul>'
        )
    }

    IndexSidebar.prototype.initEvents = function (options) {
        var view = this
        var el = this.el
        var elChar = this.elChar
        var chars = this.chars

        var boxRect = el.getBoundingClientRect()
        var boxHeight = boxRect.height
        var boxClientTop = boxRect.top

        var charOffsetX = options.charOffsetX
        var charOffsetY = options.charOffsetY

        var touching = false
        var lastChar

        // touch events
        if ('ontouchstart' in document) {
            el.addEventListener('touchstart', function (e) {
                if (!touching) {
                    e.preventDefault()
                    var t = e.touches[0]
                    start(t.clientX, t.clientY)
                    $('#item-container').css({"top":'44px'})
                }
            }, false)
            document.addEventListener('touchmove', function handler(e) {
                if (touching) {
                    e.preventDefault()
                    var t = e.touches[0]
                    el.style.background='#ccc';
                    $('#item-container').css({"top":'44px'});
                    $('.choose-county').show();
                    $('.pack').hide();
                    $('.county-box').hide();
                    $('.connect-box').empty();
                    move(t.clientX, t.clientY)
                }
            }, false)
            document.addEventListener('touchend', function (e) {
                if (touching) {
                    e.preventDefault()
                    end()
                    el.style.background='rgba(0,0,0,0)';
                }
            }, false)
        }
        // mouse events
        else {
            el.addEventListener('mousedown', function (e) {
                if (!touching) {
                    e.preventDefault()
                    start(e.clientX, e.clientY)
                }
            })
            document.addEventListener('mousemove', function (e) {
                if (touching) {
                    e.preventDefault()
                    move(e.clientX, e.clientY)
                }
            })
            document.addEventListener('mouseup', function (e) {
                if (touching) {
                    e.preventDefault()
                    end()
                }
            })
        }

        function start(clientX, clientY) {
            touching = true
            elChar.style.display = 'block'
            move(clientX, clientY)
        }

        function move(clientX, clientY) {
            var offset = calcRelativePosition(clientY)
            var percent = offset / boxHeight
            var ch = getPositionChar(percent)

            updateChar(clientX, clientY, ch)
        }

        function end() {
            touching = false
            elChar.style.display = 'none'
        }

        function updateChar(clientX, clientY, ch) {
            var x = Math.max(clientX, charOffsetX)
            var yMin = boxClientTop
            var yMax = window.innerHeight - charOffsetY
            var y = Math.min(Math.max(clientY, yMin), yMax)

            elChar.textContent = ch
            //elChar.style.left = x + 'px'
            //elChar.style.top = y + 'px'

            if (ch && lastChar !== ch) {
                lastChar = ch
                view.trigger('charChange', ch)
            }
        }

        function calcRelativePosition(clientY) {
            var y = clientY - boxClientTop
            if (y < 0) {
                y = 0
            } else if (y > boxHeight) {
                y = boxHeight
            }
            return y
        }

        // yPercent {Number} in range of [0, 1]
        function getPositionChar(yPercent) {
            var min = 1
            var max = chars.length
            var index = Math.ceil(yPercent * max)
            if (index < min) {
                index = min
            } else if (index > max) {
                index = max
            }
            return chars[index - 1]
        }
    }

    IndexSidebar.prototype.adjust = function (options) {
        var charCount = options.chars.length

        var expectHeight = window.innerHeight - options.offsetTop - options.offsetBottom
        var expectLineHeight = expectHeight / charCount
        var expectFontSize = expectLineHeight * options.lineScale

        var style = this.el.querySelector('ul').style
        style.lineHeight = expectLineHeight + 'px'
        style.fontSize = expectFontSize + 'px'
    }

    /* Event Emitter API */

    IndexSidebar.prototype.trigger = function (event, data) {
        var listeners = this._listeners && this._listeners[event]
        if (listeners) {
            listeners.forEach(function (listener) {
                listener(data)
            })
        }
    }

    IndexSidebar.prototype.on = function (event, callback) {
        this._listeners = this._listeners || {}
        var listeners = this._listeners[event] || (this._listeners[event] = [])
        listeners.push(callback)
    }

    IndexSidebar.prototype.off = function (event, callback) {
        var listeners = this._listeners && this._listeners[event]
        if (listeners) {
            var i = listeners.indexOf(callback)
            if (i > -1) {
                listeners.splice(i, 1)
                if (listeners.length === 0) {
                    this._listeners[event] = null
                }
            }
        }
    }

    return IndexSidebar

})


$('#item-container').on('touchmove',function(){
    $('.choose-county').show();
    $('.pack').hide();
    $('.county-box').hide();
    $('.connect-box').empty();
    var scrollTop= parseInt($('#item-container').scrollTop());
    if(scrollTop>0){
        $('#item-container').css({"top":'44px'});
    }else{
        $('#item-container').css({"top":'400px'});
    }
})

//获取热门城市
$(function(){
    $.ajax({
        url:'/areaC/cityHot.json',
        dataType:'json',
        type:'json',
        success:function(data){
            if(data.code==1){
                var data=data.datas;
                for(var i=0;i<data.length;i++){
                    $('<div>'+data[i].city+'</div>').appendTo($('#hotBox'));
                }
            }
        }
    })
})

//最近訪問城市
$(function(){
    $.ajax({
        url:'/user/getUserAddressHistory.json',
        dataType:'json',
        data:{
            token:getItem('token'),
        },
        type:'post',
        success:function(data){
            if(data.code!=1){
                //$('<div style="pointer-events: none;">暂无访问</div>').appendTo($('#recentBox'));
            }
            if(data.code==1){
                var data = data.datas;
                //if(data.length==0){
                //    $('<div style="pointer-events: none;">暂无访问</div>').appendTo($('#recentBox'));
                //}else{
                    for(var i=0;i<data.length;i++){
                        $('<div>'+data[i].city+'</div>').appendTo($('#recentBox'));
                    }
                //}
            }
        }
    })
})
var locationCity='';
//点击城市
mui('body').on('tap','#hotBox div,#recentBox div',function(){
    locationCity = $(this).html();
    $.ajax({
        url:'/user/updateAddressHistory.json',
        dataType:'json',
        type:'post',
        data:{
            city:locationCity,
            token:getItem('token'),
        },
        success:function(data){

        }
    })
    setCityItem('locationCity',locationCity);
    removeItem('locationCityId');
    window.location.href="index.html";
})



//地理定位
//获取经纬度
//地图定位
var lng;
var lat;

function getLocation()
{
    var geolocation = new BMap.Geolocation();

    geolocation.getCurrentPosition(function(r){

        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            lng = r.point.lng;
            lat = r.point.lat;
            $.ajax({
                url: 'https://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='+lat+','+lng+"&output="+'json',
                data: {
                    ak:'WfpHtWKGNVuic7WuI4VpiFueP4KNi1gv',
                },
                dataType: 'jsonp',
                success: function(data) {
                    //判断定位是否为空
                    if(data.result.addressComponent.city==""){
                        $('.default-city').html('定位失败，请手动选择城市');
                        $('.choose-county').hide();
                        $('.pack').hide();
                        $('.county-box').hide();
                        return;
                    }
                    //判断定位城市是否是选择城市
                    if(data.result.addressComponent.city!=getItem('locationCity')){
                        var btnArray = ['取消', '切换'];
                        mui.confirm('检测到您目前所在城市是'+data.result.addressComponent.city+'，是否切换？', '', btnArray, function(e) {
                            if (e.index == 1) {
                                $.ajax({
                                    url:'/user/updateAddressHistory.json',
                                    dataType:'json',
                                    type:'post',
                                    data:{
                                        city:data.result.addressComponent.city,
                                        token:getItem('token'),
                                    },
                                    success:function(data){

                                    }
                                })
                                removeItem('locationCityId');
                                setCityItem('locationCity',data.result.addressComponent.city);
                                window.location.href="index.html";
                            } else {

                            }
                        })
                    }
                    $('.default-city').html("当前定位城市："+data.result.addressComponent.city);
                    //选择区县，暂不排序
                    $('.choose-county').click(function(){
                        $.ajax({
                            url:'/areaC/getAreaByName.json',
                            dataType:'json',
                            data:{
                                cityName:data.result.addressComponent.city,
                            },
                            type:'post',
                            success:function(data){
                                if(data.code==1){
                                    $('.county-box').empty();
                                    $('.county-box').show();
                                    var data = data.datas;
                                    for(var i=0;i<data.length;i++){
                                        $('<div class="county" id="'+data[i].id+'">'+data[i].areaName+'</div>').appendTo($('.county-box'));
                                    }
                                    $('.choose-county').hide();
                                    $('.pack').show();
                                }
                            }
                        })
                        mui('body').on('tap','.county',function(){
                            var locationCityId = $(this).attr('id');
                            var locationCounty = $(this).html();
                            $.ajax({
                                url:'/user/updateAddressHistory.json',
                                dataType:'json',
                                type:'post',
                                data:{
                                    city:locationCity,
                                    token:getItem('token'),
                                },
                                type:'post',
                                success:function(data){

                                }
                            })
                            setCityItem('locationCityId',locationCityId);
                            //setItem('locationCounty',locationCounty);
                            //setItem('locationCity',locationCounty);
                            window.location.href="index.html";
                        })
                    })

                    $('.pack').click(function(){
                        $('.choose-county').show();
                        $('.pack').hide();
                        $('.county-box').hide();
                    })
                },
                error: function() {
                    $('.default-city').html('定位失败，请手动选择城市');
                    $('.choose-county').hide();
                    $('.pack').hide();
                    $('.county-box').hide();
                }
            })

        }
        else {
            mui.toast('failed'+this.getStatus());

        }
    })
}
getLocation();

var validCity;
//城市搜索
document.getElementById('keyword').oninput=function(){
    //输入
        if($(this).val()==""||$(this).val()=='输入城市名或拼音查询'){
            $('.connect-box').empty();
        }
    $.ajax({
        url:'/openSearchC/areaSuggest.json',
        dataType:'json',
        data:{
            keywords:$('#keyword').val(),
        },
        type:'post',
        success:function(data){
            if(data.code==1){
                if($('#keyword').val()==""){

                }else{
                    validCity = data.result.length;
                    if(data.result.length>0){
                        $('#search-right').show();
                    }else{
                        $('#search-right').hide();
                    }
                }
                $('.connect-box').empty();
                for(var i=0;i<data.result.length;i++){
                    $('<p>'+data.result[i]+'</p>').appendTo($('.connect-box'));
                }

            }
            //点击下拉
            $('.connect-box p').click(function(){
                var selectCity = $(this).html();
                setCityItem('locationCity',selectCity);
                window.location.href="index.html"
            })
            //软键盘搜索
            //$("#keyword").on('keypress',function(e) {
                //if(data.result.length>0){
                    //$('#search-right').show();
                    //var keycode = e.keyCode;
                    //var searchName = $(this).val();
                    //if(keycode=='13') {
                        //setCityItem('locationCity',searchName);
                        //window.location.href="index.html"
                    //}
                //}else{
                    //$('#search-right').hide();
                //}
            //});

            $("#search-right").on('click',function() {
                var searchName = $('#keyword').val();
                setCityItem('locationCity',searchName);
                window.location.href="index.html"
            });

        }
    })
}



//$(function(){
//    $.ajax({
//        url:'/areaC/baiDuMapQuerySort.json',
//        dataType:'json',
//        type:'post',
//        success:function(data){
//            var areaName = '';
//            console.log(data.datas[0]);
//            for(var i=0;i<data.datas.length;i++){
//                areaName+='"'+pinyin.getFullChars(data.datas[i].name)+' '+data.datas[i].name+'",'+' ';
//                //console.log(data.datas[i].name);
//            }
//            console.log(areaName);
//            //console.log($('#leftItem li').length);
//            //console.log(pinyin.getFullChars(areaName));
//        }
//    })
//})